﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace Mbs.Utils
{
    public static class PublicIPHelper
    {
        // 配置参数
        private static readonly HttpClient _client;
        private static DateTime _lastRequestTime = DateTime.MinValue;
        public static int RequestInterval { get; set; } = 30; // 秒
        public static string ApiUrl { get; set; } = "http://ip-api.com/json";

        static PublicIPHelper()
        {
            _client = new HttpClient
            {
                Timeout = TimeSpan.FromSeconds(15)
            };
            _client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
        }

        public static async Task<IpInfo> GetIPInfoAsync()
        {
            // 限流检查
            var elapsed = (DateTime.Now - _lastRequestTime).TotalSeconds;
            if (elapsed < RequestInterval)
            {
                throw new InvalidOperationException($"API 请求过于频繁，请等待 {RequestInterval - (int)elapsed} 秒后重试");
            }

            try
            {
                _lastRequestTime = DateTime.Now;

                var response = await _client.GetAsync(ApiUrl);
                response.EnsureSuccessStatusCode();

                var json = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<IpApiResponse>(json, new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                });

                if (result?.Status != "success")
                {
                    throw new ApplicationException($"API 返回失败: {result?.Message ?? "未知错误"}");
                }

                return new IpInfo
                {
                    IP = result.Query,
                    Country = result.Country,
                    Region = result.RegionName,
                    City = result.City,
                    Latitude = result.Lat,
                    Longitude = result.Lon,
                    ISP = result.Isp,
                    Timezone = result.Timezone,
                    OriginalData = json
                };
            }
            catch (TaskCanceledException ex)
            {
                throw new TimeoutException("请求超时", ex);
            }
        }

        // 嵌套数据实体类
        private class IpApiResponse
        {
            public string Status { get; set; }
            public string Message { get; set; }
            public string Query { get; set; }
            public string Country { get; set; }
            public string RegionName { get; set; }
            public string City { get; set; }
            public double Lat { get; set; }
            public double Lon { get; set; }
            public string Isp { get; set; }
            public string Timezone { get; set; }
        }
    }

    // 对外暴露的数据模型
    public class IpInfo
    {
        public string IP { get; set; }
        public string Country { get; set; }
        public string Region { get; set; }
        public string City { get; set; }
        public double Latitude { get; set; }
        public double Longitude { get; set; }
        public string ISP { get; set; }
        public string Timezone { get; set; }
        public string OriginalData { get; set; } // 原始 JSON 数据
    }

}
